<template>
  <div class="characters-preview">
    <div class="characters-header">
      <h3>人物设定</h3>
      <n-button type="primary" size="small" @click="showAddModal = true">添加人设</n-button>
    </div>
    
    <div v-if="loading" class="loading-container">
      <n-spin size="large" />
    </div>
    
    <div v-else-if="characters && characters.length > 0" class="characters-content">
      <div v-for="(character, index) in characters" :key="index" class="character-card">
        <div class="character-header">
          <h4>{{ character.name }}</h4>
          <div class="character-actions">
            <n-button size="small" type="primary" text @click="editCharacter(character)">编辑</n-button>
            <n-button size="small" type="error" text @click="deleteCharacter(character.name)">删除</n-button>
          </div>
        </div>
        
        <div class="character-details">
          <div class="detail-section">
            <h5>外在特征</h5>
            <p>{{ character.externalTraits }}</p>
          </div>
          
          <div class="detail-section">
            <h5>内在特征</h5>
            <p>{{ character.internalTraits }}</p>
          </div>
          
          <div class="detail-section">
            <h5>社会特征</h5>
            <p>{{ character.socialTraits }}</p>
          </div>
          
          <div class="detail-section">
            <h5>情感线</h5>
            <p>{{ character.emotionalArc }}</p>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="empty-content">
      <n-empty description="暂无人设内容" />
    </div>
    
    <!-- 添加/编辑人设弹窗 -->
    <n-modal v-model:show="showAddModal" preset="dialog" :title="editingCharacter ? '编辑人设' : '添加人设'" class="character-modal">
      <n-form ref="formRef" :model="formData" :rules="formRules" label-placement="left" label-width="80px">
        <n-form-item label="姓名" path="name">
          <n-input v-model:value="formData.name" placeholder="请输入人物姓名" :disabled="editingCharacter !== null" />
        </n-form-item>
        
        <n-form-item label="外在特征" path="externalTraits">
          <n-input
            v-model:value="formData.externalTraits"
            type="textarea"
            placeholder="请描述人物的外在特征，如外貌、穿着、举止等"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </n-form-item>
        
        <n-form-item label="内在特征" path="internalTraits">
          <n-input
            v-model:value="formData.internalTraits"
            type="textarea"
            placeholder="请描述人物的内在特征，如性格、价值观、思维方式等"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </n-form-item>
        
        <n-form-item label="社会特征" path="socialTraits">
          <n-input
            v-model:value="formData.socialTraits"
            type="textarea"
            placeholder="请描述人物的社会特征，如身份、职业、社会关系等"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </n-form-item>
        
        <n-form-item label="情感线" path="emotionalArc">
          <n-input
            v-model:value="formData.emotionalArc"
            type="textarea"
            placeholder="请描述人物的情感线，如情感变化、情感关系等"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </n-form-item>
      </n-form>
      
      <template #action>
        <n-button @click="showAddModal = false">取消</n-button>
        <n-button type="primary" @click="saveCharacter" :loading="saving">保存</n-button>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { NEmpty, NButton, NSpin, NModal, NForm, NFormItem, NInput, useMessage, useDialog } from 'naive-ui'
import { novelOutlineApi } from '../../book/services/novel-outline-service'
import type { CharacterProfile } from '../../book/services/book-role-service'

interface Props {
  bookId: number | undefined
}

const props = defineProps<Props>()
const message = useMessage()

const characters = ref<CharacterProfile[]>([])
const loading = ref(false)
const saving = ref(false)
const showAddModal = ref(false)
const editingCharacter = ref<CharacterProfile | null>(null)

// 表单数据
const formData = ref<CharacterProfile>({
  name: '',
  externalTraits: '',
  internalTraits: '',
  socialTraits: '',
  emotionalArc: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入人物姓名', trigger: 'blur' }
  ],
  externalTraits: [
    { required: true, message: '请输入外在特征', trigger: 'blur' }
  ],
  internalTraits: [
    { required: true, message: '请输入内在特征', trigger: 'blur' }
  ],
  socialTraits: [
    { required: true, message: '请输入社会特征', trigger: 'blur' }
  ],
  emotionalArc: [
    { required: true, message: '请输入情感线', trigger: 'blur' }
  ]
}

// 加载人设数据
const loadCharacters = async () => {
  if (!props.bookId) return
  
  try {
    loading.value = true
    const response = await novelOutlineApi.getCharacterProfilesByBookId(props.bookId)
    
    if (response.code === 0 && response.data) {
      characters.value = response.data
    } else {
      message.error(response.msg || '加载人设数据失败')
    }
  } catch (error) {
    console.error('加载人设数据失败:', error)
    message.error('加载人设数据失败')
  } finally {
    loading.value = false
  }
}

// 编辑人设
const editCharacter = (character: CharacterProfile) => {
  editingCharacter.value = character
  formData.value = { ...character }
  showAddModal.value = true
}

// 删除人设
const deleteCharacter = async (characterName: string) => {
  if (!props.bookId) return
  
  try {
    const confirmed = await new Promise<boolean>((resolve) => {
      const d = useDialog().warning({
        title: '确认删除',
        content: `确定要删除人物"${characterName}"吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          d.destroy()
          resolve(true)
        },
        onNegativeClick: () => {
          d.destroy()
          resolve(false)
        }
      })
    })
    
    if (!confirmed) return
    
    const response = await novelOutlineApi.deleteCharacterProfile(props.bookId, character.version)
    
    if (response.code === 0 && response.data) {
      characters.value = response.data
      message.success('删除成功')
    } else {
      message.error(response.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除人设失败:', error)
    message.error('删除人设失败')
  }
}

// 保存人设
const saveCharacter = async () => {
  if (!props.bookId) return
  
  try {
    saving.value = true
    
    let response
    if (editingCharacter.value) {
      // 更新人设
      const updateData = {
        bookId: props.bookId,
        characterProfile: JSON.stringify([formData.value]),
        remark: `更新角色 ${formData.value.name}`,
        version: 0 // 使用当前版本
      }
      response = await novelOutlineApi.updateCharacterProfile(updateData)
    } else {
      // 添加人设
      const addData = {
        bookId: props.bookId,
        characterProfile: JSON.stringify([formData.value]),
        remark: `新增角色 ${formData.value.name}`,
        version: 0 // 使用当前版本
      }
      response = await novelOutlineApi.addCharacterProfile(addData)
    }
    
    if (response.code === 0 && response.data) {
      characters.value = response.data
      showAddModal.value = false
      message.success(editingCharacter.value ? '更新成功' : '添加成功')
      
      // 重置表单
      resetForm()
    } else {
      message.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存人设失败:', error)
    message.error('保存人设失败')
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetForm = () => {
  editingCharacter.value = null
  formData.value = {
    name: '',
    externalTraits: '',
    internalTraits: '',
    socialTraits: '',
    emotionalArc: ''
  }
}

// 监听bookId变化
watch(() => props.bookId, () => {
  if (props.bookId) {
    loadCharacters()
  }
}, { immediate: true })
</script>

<style scoped>
.characters-preview {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
  box-sizing: border-box;
  overflow: hidden;
  background-color: #fff;
}

.characters-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-shrink: 0;
}

.characters-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
}

.characters-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  flex: 1;
  overflow-y: auto;
  padding-right: 8px;
  /* 美化滚动条 */
  scrollbar-width: thin;
  scrollbar-color: #d1d5db transparent;
}

.characters-content::-webkit-scrollbar {
  width: 6px;
}

.characters-content::-webkit-scrollbar-track {
  background: transparent;
}

.characters-content::-webkit-scrollbar-thumb {
  background-color: #d1d5db;
  border-radius: 3px;
}

.characters-content::-webkit-scrollbar-thumb:hover {
  background-color: #9ca3af;
}

.character-card {
  border: 1px solid #e0e0e6;
  border-radius: 8px;
  padding: 16px;
  background-color: #fff;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.2s ease;
}

.character-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.character-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.character-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.character-actions {
  display: flex;
  gap: 8px;
}

.character-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-section h5 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.detail-section p {
  margin: 0;
  line-height: 1.5;
  color: #333;
  font-size: 14px;
  word-break: break-word;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  gap: 16px;
}

/* 弹窗样式 */
.character-modal {
  max-width: 600px;
  width: 90%;
}
</style>